package com.example.downloaddemo.downloader;

import android.os.Handler;
import android.os.Message;

public class DownloadTask implements Runnable {

    private DownloadEntry downloadEntry;
    private boolean isPause;
    private boolean isCancel;
    private Handler mHandler;

    public DownloadTask(DownloadEntry downloadEntry, Handler mHandler) {
        this.downloadEntry = downloadEntry;
        this.mHandler = mHandler;
    }

    public void cancel() {
        isCancel = true;
    }

    public void pause() {
        isPause = true;
    }

    public void start() {
        downloadEntry.status = DownloadEntry.DownloadStatus.downloading;
        Message msg = mHandler.obtainMessage();
        msg.obj = downloadEntry;
        mHandler.sendMessage(msg);
        downloadEntry.totalLength = 1024 * 100;
        for (int i = 0; i < downloadEntry.totalLength; ) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (isPause || isCancel) {
                downloadEntry.status = isPause ? DownloadEntry.DownloadStatus.pause : DownloadEntry.DownloadStatus.cancel;
                msg = mHandler.obtainMessage();
                msg.obj = downloadEntry;
                mHandler.sendMessage(msg);
                return;
            }

            i += 1024;
            downloadEntry.setProgress(downloadEntry.getProgress() + 1204);
            msg = mHandler.obtainMessage();
            msg.obj = downloadEntry;
            mHandler.sendMessage(msg);
        }
        downloadEntry.status = DownloadEntry.DownloadStatus.completed;
        msg = mHandler.obtainMessage();
        msg.obj = downloadEntry;
        mHandler.sendMessage(msg);
    }

    @Override
    public void run() {
        start();
    }
}
